#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
浮窗UI
桌面浮窗显示关键信息
"""

import tkinter as tk
from tkinter import ttk
import time
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from game_core import GameCore
    from main import MiningSimulator

class FloatingWindow:
    """浮窗类"""
    
    def __init__(self, game_core, app):
        self.game_core = game_core
        self.app = app
        
        # 创建浮窗
        self.window = tk.Toplevel()
        self.setup_window()
        self.create_widgets()
        
        # 启动更新循环
        self.update_display()
    
    def setup_window(self):
        """设置浮窗"""
        self.window.title("挖矿摸鱼")
        self.window.geometry("320x220+100+100")
        self.window.resizable(False, False)
        
        # 设置窗口属性
        self.window.attributes("-topmost", True)  # 置顶
        self.window.attributes("-alpha", 0.9)     # 透明度
        
        # 移除标题栏装饰（可选）
        # self.window.overrideredirect(True)
        
        # 设置背景色
        self.window.configure(bg="#2C2C2C")
        
        # 绑定拖动事件
        self.window.bind("<Button-1>", self.start_drag)
        self.window.bind("<B1-Motion>", self.drag_window)
        
        # 关闭事件
        self.window.protocol("WM_DELETE_WINDOW", self.close_floating)
    
    def create_widgets(self):
        """创建控件"""
        main_frame = tk.Frame(self.window, bg="#2C2C2C", padx=10, pady=10)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = tk.Label(
            main_frame,
            text="🪙 挖矿摸鱼",
            font=("Arial", 12, "bold"),
            bg="#2C2C2C",
            fg="#FFD700"
        )
        title_label.pack()
        
        # 分隔线
        separator = tk.Frame(main_frame, height=1, bg="#555555")
        separator.pack(fill=tk.X, pady=(5, 10))
        
        # 信息显示区域
        info_frame = tk.Frame(main_frame, bg="#2C2C2C")
        info_frame.pack(fill=tk.BOTH, expand=True)
        
        # BTC余额
        self.btc_frame = self.create_info_row(info_frame, "💰 BTC:", "0.00000000")
        
        # USD估值
        self.usd_frame = self.create_info_row(info_frame, "💵 USD:", "$0.00")
        
        # 算力
        self.hashrate_frame = self.create_info_row(info_frame, "⚡ 算力:", "0 H/s")
        
        # 收益率
        self.earning_frame = self.create_info_row(info_frame, "📈 收益:", "0.00000000/s")
        
        # 挖矿状态
        self.status_frame = self.create_info_row(info_frame, "🔥 状态:", "离线")
        
        # 控制按钮区域
        button_frame = tk.Frame(main_frame, bg="#2C2C2C")
        button_frame.pack(fill=tk.X, pady=(10, 0))
        
        # 挖矿切换按钮
        self.mining_button = tk.Button(
            button_frame,
            text="开始",
            font=("Arial", 10, "bold"),
            bg="#4CAF50",
            fg="white",
            padx=12,
            pady=4,
            relief="raised",
            command=self.toggle_mining
        )
        self.mining_button.pack(side=tk.LEFT, padx=(0, 5))
        
        # 返回主界面按钮
        back_button = tk.Button(
            button_frame,
            text="返回",
            font=("Arial", 10),
            bg="#2196F3",
            fg="white",
            padx=12,
            pady=4,
            relief="raised",
            command=self.back_to_main
        )
        back_button.pack(side=tk.RIGHT, padx=(5, 0))
        
        # 虚拟宠物区域（可选）
        self.create_pet_area(main_frame)
    
    def create_info_row(self, parent, label_text, value_text):
        """创建信息行"""
        row_frame = tk.Frame(parent, bg="#2C2C2C")
        row_frame.pack(fill=tk.X, pady=2)
        
        label = tk.Label(
            row_frame,
            text=label_text,
            font=("Arial", 9),
            bg="#2C2C2C",
            fg="#CCCCCC"
        )
        label.pack(side=tk.LEFT)
        
        value_label = tk.Label(
            row_frame,
            text=value_text,
            font=("Consolas", 9, "bold"),
            bg="#2C2C2C",
            fg="#00FF00"
        )
        value_label.pack(side=tk.RIGHT)
        
        return {"label": label, "value": value_label}
    
    def create_pet_area(self, parent):
        """创建虚拟宠物区域"""
        pet_frame = tk.Frame(parent, bg="#2C2C2C", height=30)
        pet_frame.pack(fill=tk.X, pady=(5, 0))
        pet_frame.pack_propagate(False)
        
        # 宠物表情
        self.pet_label = tk.Label(
            pet_frame,
            text="🤖",
            font=("Arial", 16),
            bg="#2C2C2C",
            fg="#FFD700"
        )
        self.pet_label.pack(side=tk.LEFT)
        
        # 宠物状态文字
        self.pet_status = tk.Label(
            pet_frame,
            text="待机中...",
            font=("Arial", 8),
            bg="#2C2C2C",
            fg="#888888"
        )
        self.pet_status.pack(side=tk.RIGHT)
    
    def toggle_mining(self):
        """切换挖矿状态"""
        if self.game_core.mining_active:
            self.game_core.stop_mining()
        else:
            self.game_core.start_mining()
    
    def back_to_main(self):
        """返回主界面"""
        self.app.toggle_floating_mode()
    
    def start_drag(self, event):
        """开始拖动"""
        self.drag_data = {"x": event.x, "y": event.y}
    
    def drag_window(self, event):
        """拖动窗口"""
        if hasattr(self, 'drag_data'):
            x = self.window.winfo_x() + event.x - self.drag_data["x"]
            y = self.window.winfo_y() + event.y - self.drag_data["y"]
            self.window.geometry(f"+{x}+{y}")
    
    def update_display(self):
        """更新显示"""
        try:
            # 更新BTC余额和USD估值
            btc_amount = self.game_core.wallet["BTC"]
            btc_price = self.game_core.currencies["BTC"].price
            usd_value = btc_amount * btc_price
            
            self.btc_frame["value"].config(text=f"{btc_amount:.8f}")
            self.usd_frame["value"].config(text=f"${usd_value:,.2f}")
            
            # 更新算力
            total_hashrate = self.game_core.get_total_hashrate()
            self.hashrate_frame["value"].config(text=f"{total_hashrate:.1f} H/s")
            
            # 更新收益率
            earning_rate = self.game_core.get_earning_rate()
            self.earning_frame["value"].config(text=f"{earning_rate:.8f}/s")
            
            # 更新挖矿状态
            if self.game_core.mining_active:
                self.status_frame["value"].config(text="运行中", fg="#00FF00")
                self.mining_button.config(text="停止", bg="#f44336")
                
                # 更新宠物状态
                self.pet_label.config(text="⚡")
                self.pet_status.config(text="努力挖矿中...")
            else:
                self.status_frame["value"].config(text="离线", fg="#FF6666")
                self.mining_button.config(text="开始", bg="#4CAF50")
                
                # 更新宠物状态
                self.pet_label.config(text="😴")
                self.pet_status.config(text="摸鱼中...")
            
            # 根据收益更新颜色
            if earning_rate > 0:
                self.earning_frame["value"].config(fg="#00FF00")
            else:
                self.earning_frame["value"].config(fg="#CCCCCC")
        
        except Exception as e:
            print(f"浮窗更新错误: {e}")
        
        # 继续更新
        if hasattr(self, 'window') and self.window.winfo_exists():
            self.window.after(1000, self.update_display)  # 1秒更新一次
    
    def close_floating(self):
        """关闭浮窗"""
        self.app.toggle_floating_mode()
    
    def destroy(self):
        """销毁浮窗"""
        if hasattr(self, 'window'):
            self.window.destroy()